package com.xysoft.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xysoft.admin.common.ElementConst;
import com.xysoft.admin.common.PageModel;
import com.xysoft.admin.common.SessionInfo;
import com.xysoft.admin.dto.ActionTreeDTO;
import com.xysoft.admin.dto.AdministratorDTO;
import com.xysoft.admin.dto.OrganizationDTO;
import com.xysoft.admin.dto.RoleDTO;
import com.xysoft.admin.dto.SystemTypeDTO;
import com.xysoft.admin.service.IAdministratorService;
import com.xysoft.model.Action;
import com.xysoft.model.ActionColumn;
import com.xysoft.model.Organization;
import com.xysoft.model.Role;
import com.xysoft.model.RoleAction;
import com.xysoft.model.SystemType;
import com.xysoft.model.User;
import com.xysoft.model.UserAction;
import com.xysoft.model.UserRole;
import com.xysoft.util.DateUtil;
import com.xysoft.util.Encrypt;
import com.xysoft.util.JsonUtil;
import com.xysoft.util.RequestUtil;

@Component
@SuppressWarnings("unchecked")
public class AdministratorServiceImpl extends BaseServiceImpl implements IAdministratorService {
	
	@Transactional(readOnly = true)
	public String get(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		List<SystemType> types = this.getBaseDao().find("from SystemType s where s.deleted = 0 and belong = '0000' and front = 0");
		Map<Integer, String> typeMaps = new HashMap<Integer, String>();
		for (SystemType type : types) {
			typeMaps.put(type.getId(), type.getName());
		}
		List<Organization> organs = this.getBaseDao().find("from Organization o where o.deleted = 0 and o.keyChar like ?", 
				sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";%");
		Map<Integer, Organization> organMaps = new HashMap<Integer, Organization>();
		for (Organization organ : organs) {
			organMaps.put(organ.getId(), organ);
		}
		int page = Integer.valueOf(RequestUtil.getValue(request, "page"));
		int limit = Integer.valueOf(RequestUtil.getValue(request, "limit"));
		String hql = "from User u where u.deleted = 0 and u.front = 0 and u.organization.keyChar like ?";
		List<Object> values = new ArrayList<Object>();
		values.add(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";%");
		String username = RequestUtil.getValue(request, "username");
		if (username != null) {
			hql = hql + " and u.username like ?";
			values.add("%" + username + "%");
		}
		String truename = RequestUtil.getValue(request, "truename");
		if (truename != null) {
			hql = hql + " and u.truename like ?";
			values.add("%" + truename + "%");
		}
		String nickName = RequestUtil.getValue(request, "nickName");
		if (nickName != null) {
			hql = hql + " and u.nickName like ?";
			values.add("%" + nickName + "%");
		}
		List<User> users = this.getBaseDao().find(hql, page, limit, values);
		List<AdministratorDTO> dtos = new ArrayList<AdministratorDTO>();
		for(User user : users) {
			AdministratorDTO dto = new AdministratorDTO();
			BeanUtils.copyProperties(user, dto);
			dto.setSbirthday(DateUtil.format(user.getBirthday()));
			dto.setSlastTime(DateUtil.format(user.getLastTime()));
			dto.setSregisterDate(DateUtil.format(user.getRegisterDate()));
			int organId = user.getOrganization().getId();
			dto.setSorgan(organId);
			Organization tempOrgan = organMaps.get(organId);
			dto.setSorganName(tempOrgan.getName());
			int typeId = user.getSystemType().getId();
			dto.setSsystemType(typeId);
			dto.setSsystemTypeName(typeMaps.get(typeId));
			dtos.add(dto);
		}
		long count = this.getBaseDao().count("select count(*) " + hql, values);
		PageModel pm = new PageModel();
		pm.setTotal(count);
		pm.setDatas(dtos);
		return JsonUtil.toStringFromObject(pm);
	}
	
	@Transactional
	public String getAction(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		List<String> actions = sessionInfo.getActions();
		List<Action> acts = this.getBaseDao().find("from Action where front = 0 and level >= ?",
				sessionInfo.getTypeValue().length());
		Map<String, Action> actMaps = new HashMap<String, Action>();
		Map<Integer, Integer> aidMaps = new HashMap<Integer, Integer>();
		for (Action act : acts) {
			actMaps.put(act.getCode(), act);
			if (act.getCode().indexOf("?index") != -1) {
				aidMaps.put(act.getColumn().getId(), act.getId());
			}
		}
		List<ActionColumn> acs = this.getBaseDao().find("from ActionColumn order by level desc");
		Map<Integer, ActionColumn> colMaps = new HashMap<Integer, ActionColumn>();
		Map<Integer, ActionTreeDTO> trees = new HashMap<Integer, ActionTreeDTO>();
		for (ActionColumn ac : acs) {
			colMaps.put(ac.getId(), ac);
		}
		Map<Integer, ActionTreeDTO> dtos = new HashMap<Integer, ActionTreeDTO>();
		for (String action : actions) {
			if (!actMaps.containsKey(action)) continue;
			Action aid = actMaps.get(action);
			int id = aid.getColumn().getId();
			ActionColumn ac = colMaps.get(id);
			if (dtos.containsKey(id)) {
				if (aid.isLeaf()) continue;
				ActionTreeDTO dto = dtos.get(id);
				List<ActionTreeDTO> lst = dto.getChildren();
				ActionTreeDTO dtoOne = new ActionTreeDTO();
				dtoOne.setId(aid.getId());
				dtoOne.setText(aid.getKeyName());
				dtoOne.setChecked(false);
				dtoOne.setExpanded(false);
				dtoOne.setIcon("../manage/pic/menu/11.png");
				dtoOne.setLeaf(true);
				lst.add(dtoOne);
				dto.setChildren(lst);
				dtos.put(id, dto);
			} else {
				if (aid.isLeaf()) {
					ActionTreeDTO dto = new ActionTreeDTO();
					dto.setId(aid.getId());
					dto.setChecked(false);
					dto.setExpanded(false);
					dto.setIcon("../manage/pic/menu/" + ac.getIcon());
					dto.setLeaf(false);
					dto.setText(ac.getName());
					dtos.put(id, dto);
				} else {
					int pact = aidMaps.get(id);
					ActionTreeDTO dto = new ActionTreeDTO();
					dto.setId(pact);
					dto.setChecked(false);
					dto.setExpanded(false);
					dto.setIcon("../manage/pic/menu/" + ac.getIcon());
					dto.setLeaf(false);
					dto.setText(ac.getName());
					List<ActionTreeDTO> lst = dto.getChildren();
					//操作节点
					ActionTreeDTO dtoOne = new ActionTreeDTO();
					dtoOne.setId(aid.getId());
					dtoOne.setText(aid.getKeyName());
					dtoOne.setChecked(false);
					dtoOne.setExpanded(false);
					dtoOne.setIcon("../manage/pic/menu/11.png");
					dtoOne.setLeaf(true);
					lst.add(dtoOne);
					dto.setChildren(lst);
					dtos.put(id, dto);
				}
			}
		}
		for (ActionColumn ac : acs) {
			ActionTreeDTO dto = null;
			if (ac.getLevel() == 3) {
				if (!dtos.containsKey(ac.getId())) continue;
				dto = dtos.get(ac.getId());
				trees.put(ac.getId(), dto);
				int pid = 0 - ac.getParent().getId();
				ActionColumn pac = colMaps.get(0 - pid);
				ActionTreeDTO pdto = null;
				if (trees.containsKey(pid)) {
					pdto = trees.get(pid);
					List<ActionTreeDTO> lst = pdto.getChildren();
					lst.add(dto);
					pdto.setChildren(lst);
					trees.put(pid, pdto);
				} else {
					pdto = new ActionTreeDTO();
					pdto.setId(pid);
					pdto.setChecked(false);
					pdto.setExpanded(true);
					pdto.setLeaf(false);
					pdto.setIcon("../manage/pic/menu/" + pac.getIcon());
					pdto.setText(pac.getName());
					List<ActionTreeDTO> lst = pdto.getChildren();
					lst.add(dto);
					pdto.setChildren(lst);
					trees.put(pid, pdto);
				}
			} else if (ac.getLevel() == 2) {
				if (!trees.containsKey(0 - ac.getId())) continue;
				dto = trees.get(0 - ac.getId());
				int pid = 0 - ac.getParent().getId();
				ActionColumn pac = colMaps.get(0 - pid);
				ActionTreeDTO pdto = null;
				if (trees.containsKey(pid)) {
					pdto = trees.get(pid);
					List<ActionTreeDTO> lst = pdto.getChildren();
					lst.add(dto);
					pdto.setChildren(lst);
					trees.put(pid, pdto);
				} else {
					pdto = new ActionTreeDTO();
					pdto.setId(pid);
					pdto.setChecked(false);
					pdto.setExpanded(true);
					pdto.setLeaf(false);
					pdto.setParent(9999);
					pdto.setIcon("../manage/pic/menu/" + pac.getIcon());
					pdto.setText(pac.getName());
					List<ActionTreeDTO> lst = pdto.getChildren();
					lst.add(dto);
					pdto.setChildren(lst);
					trees.put(pid, pdto);
				}
			}
		}
		//返回数据集
		List<ActionTreeDTO> autos = new ArrayList<ActionTreeDTO>();
		for (ActionTreeDTO atd : trees.values()) {
			if (atd.getParent() == 9999) {
				autos.add(atd);
			}
		}
		return JsonUtil.toString(autos);
	}

	@Transactional
	public String getRole(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		List<RoleAction> ras = this.getBaseDao().find("from RoleAction ra where ra.role.organization.id = ?", 
				sessionInfo.getOrgId());
		Map<Integer, String> maps = new HashMap<Integer, String>();
		for (RoleAction ra : ras) {
			int id = ra.getRole().getId();
			if (maps.containsKey(id)) {
				maps.put(id, maps.get(id) + ra.getAction().getId() + ";");
			} else {
				maps.put(id, ra.getAction().getId() + ";");
			}
		}
		String hql = "from Role r where r.deleted = 0 and r.front = 0 and r.organization.id = ?";
		List<Object> values = new ArrayList<Object>();
		values.add(sessionInfo.getOrgId());
		hql = hql + " order by r.id desc";
		List<Role> roles = this.getBaseDao().find(hql, values);
		List<RoleDTO> dtos = new ArrayList<RoleDTO>();
		Organization organ = (Organization)this.getBaseDao().get(Organization.class, sessionInfo.getOrgId()); 
		for (Role role : roles) {
			RoleDTO dto = new RoleDTO();
			BeanUtils.copyProperties(role, dto);
			dto.setOrgan(organ.getName());
			dto.setRule(maps.get(role.getId()));
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public Map<String, Object> config(HttpServletRequest request,
			HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int userId = Integer.valueOf(RequestUtil.getValue(request, "id"));
		User user = (User)this.getBaseDao().get(User.class, userId);
		if (!user.getOrganization().getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") 
				|| user.isDeleted()) return null;
		Set<UserRole> userRoles = user.getUserRoles();
		Map<Integer, UserRole> urMaps = new HashMap<Integer, UserRole>();
		for (UserRole ur : userRoles) {
			urMaps.put(ur.getRole().getId(), ur);
		}
		//获取角色对象.
		String rolestr = RequestUtil.getValue(request, "rolestr");
		List<Role> roles = this.getBaseDao().find("from Role r where r.front = 0 and r.id in (" + rolestr 
				+ ") and r.organization.id = ?", sessionInfo.getOrgId());
		for (Role role : roles) {
			int id = role.getId();
			if (!urMaps.containsKey(id)) {
				UserRole ur = new UserRole(); 
				ur.setRole(role);
				ur.setUser(user);
				this.getBaseDao().save(ur);
			} else {
				urMaps.remove(id);
			}
		}
		//获取角色所对应的权限对象
		List<RoleAction> ras = this.getBaseDao().find("from RoleAction ra where ra.role.id in (" + rolestr + ")");
		List<Integer> rasints = new ArrayList<Integer>();
		for (RoleAction ra : ras) {
			int id = ra.getAction().getId();
			if (!rasints.contains(id)) {
				rasints.add(id);
			}
		}
		//获取所有权限对象
		List<String> actions = sessionInfo.getActions();
		String actStr = "'0'";
		for (String action : actions) {
			actStr = actStr + ",'" + action + "'";
		}
		List<Action> acts = this.getBaseDao().find("from Action a where a.code in (" + actStr 
				+ ") and a.front = 0 and a.level >= ?", sessionInfo.getTypeValue().length());
		Map<Integer, Action> actMaps = new HashMap<Integer, Action>();
		for (Action act : acts) {
			actMaps.put(act.getId(), act);
		}
		String autostr = RequestUtil.getValue(request, "autostr");
		List<Integer> yesMaps = new ArrayList<Integer>();
		String[] ids = autostr.split(";");
		Integer[] intIds = new Integer[ids.length];
		if (!"".equals(autostr)) {
			for (int i = 0; i < ids.length; i++) {
				intIds[i] = Integer.valueOf(ids[i]);
			}
			for (Integer id : intIds) {
				if (rasints.contains(id)) {
					rasints.remove(id);
				} else {
					yesMaps.add(id);
				}
			}
		}
		Set<UserAction> uas = user.getUserActions();
		Map<Integer, UserAction> uasMaps = new HashMap<Integer, UserAction>();
		for (UserAction ua : uas) {
			uasMaps.put(ua.getAction().getId(), ua);
		}
		for (Integer id : rasints) {
			if (uasMaps.containsKey(id)) {
				UserAction ssa = uasMaps.get(id);
				if (!ssa.isEnable()) {
					uasMaps.remove(id);
				} else {
					UserAction dto = new UserAction();
					dto.setAction(actMaps.get(id));
					dto.setEnable(false);
					dto.setUser(user);
					dto.setRule(0);
					this.getBaseDao().save(dto);
				}
			} else {
				UserAction dto = new UserAction();
				dto.setAction(actMaps.get(id));
				dto.setEnable(false);
				dto.setUser(user);
				dto.setRule(0);
				this.getBaseDao().save(dto);
			}
		}
		for (Integer id : yesMaps) {
			if (uasMaps.containsKey(id)) {
				UserAction ssa = uasMaps.get(id);
				if (ssa.isEnable()) {
					uasMaps.remove(id);
				} else {
					UserAction dto = new UserAction();
					dto.setAction(actMaps.get(id));
					dto.setEnable(true);
					dto.setUser(user);
					dto.setRule(0);
					this.getBaseDao().save(dto);
				}
			} else {
				UserAction dto = new UserAction();
				dto.setAction(actMaps.get(id));
				dto.setEnable(true);
				dto.setUser(user);
				dto.setRule(0);
				this.getBaseDao().save(dto);
			}
		}
		user.setUserActions(null);
		for (UserAction ua : uasMaps.values()) {
			this.getBaseDao().delete(ua);
		}
		//删除未授权的角色
		user.setUserRoles(null);
		for (UserRole ur : urMaps.values()) {
			this.getBaseDao().delete(ur);
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(2);
		modelMap.put("success", true);
		modelMap.put("msg", "保存成功！");
		return modelMap;
	}

	@Transactional
	public Map<String, Object> getAuto(HttpServletRequest request,
			HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int userId = Integer.valueOf(RequestUtil.getValue(request, "id"));
		User user = (User)this.getBaseDao().get(User.class, userId);
		if (!user.getOrganization().getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") 
				|| user.isDeleted()) return null;
		Set<UserRole> urs = user.getUserRoles();
		String rolestr = "";
		String tempstr = "0";
		for (UserRole ur : urs) {
			rolestr = rolestr + ur.getRole().getId() + ";";
			tempstr = tempstr + "," + ur.getRole().getId();
		}
		List<Integer> actLst = new ArrayList<Integer>();
		List<RoleAction> ras = this.getBaseDao().find("from RoleAction ra where ra.role.id in (" + tempstr + ")");
		for (RoleAction ra : ras) {
			actLst.add(ra.getAction().getId());
		}
		List<UserAction> uas = this.getBaseDao().find("from UserAction ua where ua.user.id = ?", userId);
		for (UserAction ua : uas) {
			Integer id = ua.getAction().getId();
			if (actLst.contains(id)) {
				if (!ua.isEnable()) {
					actLst.remove(id);
				}
			} else {
				actLst.add(id);
			}
		}
		String autostr = "";
		for (Integer actId : actLst) {
			autostr = autostr + actId + ";";
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(4);
		modelMap.put("success", true);
		modelMap.put("msg", "获取成功！");
		modelMap.put("rolestr", rolestr);
		modelMap.put("autostr", autostr);
		return modelMap;
	}

	@Transactional
	public String getSystemType(HttpServletRequest request, HttpSession session) {
		List<SystemType> types = this.getBaseDao().find("from SystemType s where s.deleted = 0 and belong = '0000' and front = 0");
		List<SystemTypeDTO> dtos = new ArrayList<SystemTypeDTO>();
		for (SystemType st : types) {
			SystemTypeDTO dto = new SystemTypeDTO();
			dto.setId(st.getId());
			dto.setName(st.getName());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}
	
	@Transactional(readOnly = true)
	public String getOrgan(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		User user = (User)this.getBaseDao().get(User.class, sessionInfo.getUser().getId());
		Organization organ = user.getOrganization();
		String node = request.getParameter("node");
		//查询SQL语句
		String hql = "from Organization o where o.deleted = 0";
		//查询SQL值
		List<Object> values = new ArrayList<Object>();
		if (node == null || "root".equals(node)) {
			hql = hql + " and o.parent.id = ?";
			values.add(organ.getId());
		} else {
			hql = hql + " and o.keyChar like ? and o.parent.id = ?";
			values.add(organ.getKeyChar() + "%");
			values.add(Integer.valueOf(node));
		}
		List<Organization> organizations = this.getBaseDao().find(hql, values);
		List<OrganizationDTO> dtos = new ArrayList<OrganizationDTO>();
		for (Organization oo : organizations) {
			OrganizationDTO dto = new OrganizationDTO();
			BeanUtils.copyProperties(oo, dto);
			if (oo.getNumber() > 0) {
				dto.setExpandable(true);
				dto.setLeaf(false);
			} else {
				dto.setExpandable(false);
				dto.setLeaf(true);
			}
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public Map<String, Object> addOrModify(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int organId = Integer.valueOf(RequestUtil.getValue(request, "sorgan"));
		Organization organ = (Organization)this.getBaseDao().get(Organization.class, organId);
		if (!organ.getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") 
				|| organ.isDeleted()) return null;
		Map<String,Object> modelMap = new HashMap<String,Object>(4);
		modelMap.put("success", true);
		modelMap.put("obj", false);
		modelMap.put("title", "保存失败！");
		String username = RequestUtil.getValue(request, "username").trim();
		if ("".equals(username) || username.length() < 6) {
			modelMap.put("msg", "登录名不能为空（大于或等于6个字符）.");
			return modelMap;
		} 
		long count = this.getBaseDao().count("select count(*) from User u where u.deleted = 0 and  u.username = ?", 
				username);
		String idStr = RequestUtil.getValue(request, "id"); 
		User user = null;
		String password = RequestUtil.getValue(request, "password").trim();
		if ("".equals(idStr)) {
			if (count > 0) {
				modelMap.put("msg", "登录名已存在.");
				return modelMap;
			}
			if ("".equals(password)) {
				modelMap.put("msg", "登录密码不能为空（大于或等于6个字符）.");
				return modelMap;
			}
			user = new User();
			user.setDeleted(false);
			user.setFront(false);
			user.setLastTime(new Date());
			user.setRegisterDate(new Date());
			user.setPic(false);
		} else {
			user = (User)this.getBaseDao().get(User.class, Integer.valueOf(idStr));
			if (user.isFront() || user.isDeleted() || !user.getOrganization().getKeyChar()
					.startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";")) return null;
			if (!username.equals(user.getUsername()) && count > 0) {
				modelMap.put("msg", "登录名已存在.");
				return modelMap;
			}
		}
		
		String repassword = RequestUtil.getValue(request, "repassword").trim();
		if (!"".equals(password) && (password.length() < 6 || !password.equals(repassword))) {
			modelMap.put("msg", "密码不合法.");
			return modelMap;
		}
		user.setUsername(username);
		if (!"".equals(password)) {
			user.setPassword(Encrypt.md5AndSha(password));
		}
		user.setEnabled(Boolean.valueOf(RequestUtil.getValue(request, "enabled")));
		user.setLimited(Boolean.valueOf(RequestUtil.getValue(request, "limited")));
		user.setMail(RequestUtil.getValue(request, "mail"));
		user.setMotto(RequestUtil.getValue(request, "motto"));
		user.setNickName(RequestUtil.getValue(request, "nickName"));
		user.setOrganization(organ);
		user.setPhone(RequestUtil.getValue(request, "phone"));
		user.setQq(RequestUtil.getValue(request, "qq"));
		user.setRemark(RequestUtil.getValue(request, "remark"));
		user.setSex(Integer.valueOf(RequestUtil.getValue(request, "sex")));
		user.setTruename(RequestUtil.getValue(request, "truename"));
		SystemType type = (SystemType)this.getBaseDao().get(SystemType.class, 
				Integer.parseInt(RequestUtil.getValue(request, "ssystemType")));
		user.setSystemType(type);
		this.getBaseDao().save(user);
		modelMap.put("title", "保存成功！");
		modelMap.put("msg", "");
		modelMap.put("obj", true);
		return modelMap;
	}

	@Transactional
	public Map<String, Object> remove(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		User user = (User)this.getBaseDao().get(User.class, 
				Integer.valueOf(RequestUtil.getValue(request, "id")));
		if (!user.getOrganization().getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") 
				|| user.isDeleted() || user.isFront()) return null;
		user.setDeleted(true);
		this.getBaseDao().save(user);
		Map<String,Object> modelMap = new HashMap<String,Object>(4);
		modelMap.put("success", true);
		modelMap.put("ok", true);
		modelMap.put("msg", "删除成功！");
		return modelMap;
	}

	@Transactional
	public Map<String, Object> pic(HttpServletRequest request, HttpSession session) {
		SessionInfo sessionInfo = RequestUtil.getSession(request, session);
		int userId = Integer.valueOf(RequestUtil.getValue(request, "id"));
		User user = (User)this.getBaseDao().get(User.class, userId);
		if (!user.getOrganization().getKeyChar().startsWith(sessionInfo.getKeyChar() + sessionInfo.getOrgId() + ";") 
				|| user.isDeleted() || user.isFront()) return null;
		String targetFile = request.getSession().getServletContext().getRealPath(ElementConst.USERPICPATH) 
				+ File.separator;
		File target = new File(targetFile);
		if (!target.exists()) target.mkdirs();
		MultipartHttpServletRequest mulrequest = (MultipartHttpServletRequest)request;
		List<MultipartFile> files = mulrequest.getFiles("file");
		if (files.size() > 0) {
			CommonsMultipartFile file = (CommonsMultipartFile)files.get(0);
			DiskFileItem fileItem = (DiskFileItem) file.getFileItem();
			try {
				File fr = new File(targetFile + userId + this.getFileName(fileItem.getName()));
				FileCopyUtils.copy(file.getBytes(), fr);
				if (!user.isPic()) {
					user.setPic(true);
					this.getBaseDao().save(user);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("success", true);
		modelMap.put("title", "上传成功！");
		modelMap.put("msg", "");
		return modelMap;
	}
	
	/**
	 * 获取文件扩展名 .
	 */
	private String getFileName(String str) {
		int index = str.lastIndexOf(".");
		if (-1 != index) {
			return str.substring(index);
		} else {
			return str;
		}
	}

}
